<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>indexedDB</title>
</head>
<body>
	<input type="button" value="连接数据库" onclick="connectDB();" />
	<input type="button" value="关闭数据库" onclick="closeDB();" />
	<input type="button" value="更新数据库" onclick="updateDB();" />
	<input type="button" value="创建对象仓库" onclick="creatObjectStore();" />
	
	<script>
		var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
		var idb;
		//连接数据库
		function connectDB() {
			var dbName = 'hyData';
			var dbVersion = '201702141';
			var dbConnect = indexedDB.open(dbName,dbVersion);//一个IDBOpenDBRequest对象
			dbConnect.onsuccess = function(e) {  //连接成功
				idb = e.target.result;
				console.log("数据库连接成功" + idb);
			}
			dbConnect.onerror = function(e) {  //连接失败
				console.log("连接失败");
			}
		}
		//关闭数据库
		function closeDB() {
			idb.close();
			console.log("数据库已经关闭")
		}
		//更新数据库
		function updateDB() {
			var dbName = 'hyData';
			var dbVersion = '201702142';
			var dbConnect = indexedDB.open(dbName,dbVersion);//一个IDBOpenDBRequest对象
			dbConnect.onsuccess = function(e) {  //连接成功
				idb = e.target.result;
				console.log("数据库连接成功" + idb);
			}
			dbConnect.onerror = function(e) {  //连接失败
				console.log("连接失败");
			}
			dbConnect.onupgradeneeded = function(e) { //当连接的数据库版本号大于当前版本号时触发该事件
				idb = e.target.result;
				var tx = e.target.transaction;
				var oldVersion = e.oldVersion;
				var newVersion = e.newVersion;
				console.log("数据库更新成功，旧版本号是：" + oldVersion + ",新版本号是：" + newVersion);
			}
		}
		//创建对象仓库
		function creatObjectStore() {
			var dbName = 'hyData';
			var dbVersion = '201702143';
			var dbConnect = indexedDB.open(dbName,dbVersion);//一个IDBOpenDBRequest对象
			dbConnect.onsuccess = function(e) {  //连接成功
				idb = e.target.result;
				console.log("数据库连接成功" + idb);
			}
			dbConnect.onerror = function(e) {  //连接失败
				console.log("连接失败");
			}
			dbConnect.onupgradeneeded = function(e) { //当连接的数据库版本号大于当前版本号时触发该事件
				idb = e.target.result;
				var tx = e.target.transaction;
				var name = 'Users';
				var optionalParameters = {
					keyPath: 'userId',
					autoIncrement: true
				};
				var store = idb.createObjectStore(name,optionalParameters);
				
			}
		}
	</script>
	
</body>
</html>